//获取url参数

//URLSearchParams方法
//创建一个URLSearchParams实例
// const urlSearchParams = new URLSearchParams(window.location.search)
// const params = Object.fromEntries(urlSearchParams.entries())

//split方法
function getParams(url){
    const res = {}
    if(url.includes('?')){
        const str = url.split('?')[1]
        const arr = str.split('&')
        arr.forEach(item=>{
            let key = item.split('=')[0]
            let value = item.split('=')[1]
            res[key] = decodeURIComponent(value) //解码
        })
    }
    return res
}

// 测试
const user = getParams('http://www.baidu.com?user=%E9%98%BF%E9%A3%9E&age=16')
console.log(user) // { user: '阿飞', age: '16' }


//设置url参数
function setParams(url,obj){
    let str =  ''
    for(let key in obj){
        if(obj.hasOwnProperty(key)){
            if(str === ''){
                str += `${key}=${obj[key]}`
            } else {
                str += `&${key}=${obj[key]}`
            }
        }
    }
    if(url.includes('?')){
        str = `&${str}`
    } else {
        str = `?${str}`
    }
    return url + str
}

console.log(setParams('http//www.baidu.com/course',{name: '笔者真帅',value: '666'}))
console.log(setParams('http//www.baidu.com/course?username=xm',{name: '笔者真帅',value: '666'}))

function setParams1(obj,isParam){
    let str = ''
    for(let key in obj){
        if(obj.hasOwnProperty(key)){
            if(str === ''){
                str += `${key}=${obj[key]}`
            } else {
                str += `&${key}=${obj[key]}`
            }
        }
    }

    if(isParam){
        str = `&${str}`
    } else {
        str = `?${str}`
    }
    return str
}